﻿using System.IO;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.iOS.Xcode;
using UnityEditor.Callbacks;
using UnityEditor.XCodeEditor;
#endif
using System.Collections;

public class iOS_PBXProject : MonoBehaviour
{
    [PostProcessBuild]
    public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject)
    {

        // BuildTarget需为iOS
        if (buildTarget != BuildTarget.iOS)
            return;

        // 初始化
        var projectPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);

        PBXProject pbxProject = new PBXProject();
        pbxProject.ReadFromFile(projectPath);

        var unityMainTargetGuidMethod = pbxProject.GetType().GetMethod("GetUnityMainTargetGuid");
        var unityFrameworkTargetGuidMethod = pbxProject.GetType().GetMethod("GetUnityFrameworkTargetGuid");

        string mainTargetGuid = "";
        string unityFrameworkTargetGuid = "";

        if (unityMainTargetGuidMethod != null && unityFrameworkTargetGuidMethod != null)
        {
            mainTargetGuid = (string)unityMainTargetGuidMethod.Invoke(pbxProject, null);
            unityFrameworkTargetGuid = (string)unityFrameworkTargetGuidMethod.Invoke(pbxProject, null);
        }
        else
        {
            mainTargetGuid = pbxProject.TargetGuidByName("Unity-iPhone"); //依据主项目名操作，若主项目名改动了，则需要这里对应同步一下
            unityFrameworkTargetGuid = mainTargetGuid;
        }


        //** Capability修改
        //添加通知
        //var capManager = new ProjectCapabilityManager(MyApi.iOS.Xcode.PBXProject.GetPBXProjectPath(pathToBuiltProject), "xxxx.entitlements", MyApi.iOS.Xcode.PBXProject.GetUnityTargetName());
        //capManager.AddPushNotifications(true);
        //capManager.WriteToFile();
        pbxProject.AddCapability(mainTargetGuid, PBXCapabilityType.SignInWithApple);
        //pbxProject.AddCapability(mainTargetGuid, PBXCapabilityType.InAppPurchase);
        pbxProject.AddCapability(mainTargetGuid, PBXCapabilityType.PushNotifications);

        //** buildsetting 修改
        //添加flag
        pbxProject.AddBuildProperty(mainTargetGuid, "OTHER_LDFLAGS", "$(inherited)");
        // 关闭Bitcode
        pbxProject.SetBuildProperty(mainTargetGuid, "ENABLE_BITCODE", "NO");
        pbxProject.SetBuildProperty(mainTargetGuid, "CLANG_MODULES_AUTOLINK", "NO");

        //** 本地资源文件添加
        //var fileGUID1 = pbxProject.AddFile("Frameworks/Plugins/iOS/UjoySDKResources.bundle", "Frameworks/Plugins/iOS/UjoySDKResources.bundle", PBXSourceTree.Source);
        //pbxProject.AddFileToBuild(mainTargetGuid, fileGUID1);       
        //var fileGUID2 = pbxProject.AddFile("Frameworks/Plugins/iOS/UjoySDK.framework", "Frameworks/Plugins/iOS/UjoySDK.framework", PBXSourceTree.Source);
        //pbxProject.AddFileToBuild(mainTargetGuid, fileGUID2);

        //本地资源文件添加
        var fileGUID = pbxProject.AddFile(Application.dataPath +  "/Plugins/iOS/GoogleService-Info.plist", "Libraries/Plugins/iOS/GoogleService-Info.plist");
        pbxProject.AddFileToBuild(mainTargetGuid, fileGUID);
        var ujoyServiceinfoGUID = pbxProject.AddFile(Application.dataPath + "/Plugins/iOS/UjoyService-info.plist", "Libraries/Plugins/iOS/UjoyService-info.plist");
        pbxProject.AddFileToBuild(mainTargetGuid, ujoyServiceinfoGUID);

        //添加lib
        //AddLibToProject(pbxProject, targetGuid, "libsqlite3.tbd");
        //AddLibToProject(pbxProject, targetGuid, "libc++.tbd");
        //AddLibToProject(pbxProject, targetGuid, "libz.tbd");

        // 应用修改提交
        File.WriteAllText(projectPath, pbxProject.WriteToString());

        // 修改Info.plist文件
        var plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
        var plist = new PlistDocument();
        plist.ReadFromFile(plistPath);

        // 插入URL Scheme到Info.plsit（理清结构）
        var schemeArrays = plist.root.CreateArray("CFBundleURLTypes");

        //fb
        var urlDict1 = schemeArrays.AddDict();
        urlDict1.SetString("CFBundleTypeRole", "Editor");
        urlDict1.SetString("CFBundleURLName", "fb");//这个内容可以写任意内容，一般只作为标识
        var urlInnerArray1 = urlDict1.CreateArray("CFBundleURLSchemes");
        urlInnerArray1.AddString("your fb appkey");//将内容替换成对应的AppKey

        var urlDict2 = schemeArrays.AddDict();
        urlDict2.SetString("CFBundleTypeRole", "Editor");
        urlDict2.SetString("CFBundleURLName", "google");
        var urlInnerArray2 = urlDict2.CreateArray("CFBundleURLSchemes");
        urlInnerArray2.AddString("com.googleusercontent.apps.363718655995-f2c8c100142s2qqd5168d4nqmuum9130");

        //var urlDict3 = schemeArrays.AddDict();
        //urlDict3.SetString("CFBundleTypeRole", "Editor");
        //urlDict3.SetString("CFBundleURLName", "naver");
        //var urlInnerArray3 = urlDict3.CreateArray("CFBundleURLSchemes");
        //urlInnerArray3.AddString("com.ujoy.games.ziyue");


        //设置白名单 LSApplicationQueriesSchemes（数组）
        PlistElementArray loginChannelsArr;
        loginChannelsArr = plist.root.CreateArray("LSApplicationQueriesSchemes");
        loginChannelsArr.AddString("fbapi");
        loginChannelsArr.AddString("fbapi20130214");
        loginChannelsArr.AddString("fbapi20130410");
        loginChannelsArr.AddString("fbapi20130702");
        loginChannelsArr.AddString("fbapi20131010");
        loginChannelsArr.AddString("fbapi20131219");
        loginChannelsArr.AddString("fbapi20140410");
        loginChannelsArr.AddString("fbapi20140116");
        loginChannelsArr.AddString("fbapi20150313");
        loginChannelsArr.AddString("fbapi20150629");
        loginChannelsArr.AddString("fbapi20160328");
        loginChannelsArr.AddString("fbauth");
        loginChannelsArr.AddString("fbauth2");
        loginChannelsArr.AddString("fb-messenger-share-api");
        loginChannelsArr.AddString("fbshareextension");
        loginChannelsArr.AddString("naversearchapp");
        loginChannelsArr.AddString("naversearchthirdlogin");


        
        plist.root.SetString("NSUserTrackingUsageDescription", "请填入正确IDFA描述"); //IDFA权限

        plist.root.SetString("FacebookAppID", "214651689612651"); //若包含facebook的相关业务则需要填入 appid
        plist.root.SetString("FacebookDisplayName", "");//若包含facebook的相关业务则需要填入  fb对外展示的应用名字

        // 应用修改
        plist.WriteToFile(plistPath);


        //插入代码
        //读取UnityAppController.mm文件
        string unityAppControllerPath = pathToBuiltProject + "/Classes/UnityAppController.mm";
        XClass UnityAppController = new XClass(unityAppControllerPath);

        //在指定代码后面增加一行代码
        UnityAppController.WriteBelow("#include \"PluginBase/AppDelegateListener.h\"", "#import <UjoySDK/UjoySDKManager.h>");

        string newCode1 = "\n" +
                    "    [UjoySDKManager application:application didFinishLaunchingWithOptions:launchOptions];\n" +
                    "    \n"
                    ;
        //在指定代码后面增加一大行代码
        UnityAppController.WriteBelow("// if you wont use keyboard you may comment it out at save some memory", newCode1);


        string newCode2 = "\n" +
                    "    [UjoySDKManager applicationDidBecomeActive:application];\n" +
                    "    \n"
                    ;
        UnityAppController.WriteBelow("// need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler", newCode2);


    }

    //添加lib方法
    static void AddLibToProject(PBXProject inst, string targetGuid, string lib)
    {
        string fileGuid = inst.AddFile("usr/lib/" + lib, "Frameworks/" + lib, PBXSourceTree.Sdk);
        inst.AddFileToBuild(targetGuid, fileGuid);
    }

}
